package com.itheima05;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

/**
 * @author Xiao
 * @date 2021/7/25
 */
public class GenericityDemo02 {
    /**
     * 定义方法：参数是两个   1.ArrayList集合   2.索引
     *      查找对应索引位置的元素并返回。
     */
    public static void main(String[] args) {
        ArrayList<String> list1 = new ArrayList<>();
        Collections.addAll(list1, "aaa", "bbb", "ccc");
        ArrayList<Integer> list2 = new ArrayList<>();
        Collections.addAll(list2, 111,222,333);
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入索引：");
        int index = sc.nextInt();
        String s = getIndex(list1, index);
        Integer i = getIndex(list2, index);
        System.out.println("indexInList1:" + s);
        System.out.println("indexInList2:" + i);

    }
    private static <E> E getIndex(ArrayList<E> list, int index){
        if (list == null) {
            //IllegalArgumentException 非法参数异常
            throw new IllegalArgumentException("集合不能为null");
        }
        if (index > list.size() - 1 || index < 0) {
            throw new IndexOutOfBoundsException("索引不在正确的范围内");
        }
        return list.get(index);
    }
}
